package neety.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/10/6 16:02
 */

public class NeetyClient {
    private String host;
    private int port;

    public NeetyClient(int port) {
        this("localhost", port);
    }

    public NeetyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(this.host, this.port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            System.out.println("正在连接中...");
                            socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("utf8")));
                            socketChannel.pipeline().addLast(new ClientHandler());
                            socketChannel.pipeline().addLast(new ByteArrayEncoder());
                            socketChannel.pipeline().addLast(new ChunkedWriteHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect().sync();
            System.out.println("连接成功......");
            channelFuture.channel().closeFuture().sync();
            System.out.println("连接已关闭");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new NeetyClient("127.0.0.1", 8888).start();
    }
}
